<script setup>
import { ref,onMounted,watch } from 'vue'
import { Plus, Edit, Delete, Minus, Male, Female } from '@element-plus/icons-vue'
import { queryPageApi,queryEmpByIdApi,addEmpApi,updateyEmpApi,delEmpApi } from '../../api/emp'
import { queryAllApi as queryAllDept} from '@/api/dept'
import {ElMessage,ElNotification,ElMessageBox } from 'element-plus'

// 查询表单
const formEmp = ref({
  name: '',
  gender: '',
  entryDate: '',
  begin : '',
  end : '',
  page: 1,
  pageSize: 10
})

// 员工列表
const empList = ref([])
// 页数
const pageSize = ref(10)
// 页码
const currentPage = ref(1)
// 总数据
const total = ref(0)
// 添加修改员工对话框的显示
const dialogFormVisible = ref(false)
// 添加修改员工对话框的标题
const dialogTitle = ref('')
// 修改增加表单
const diglogFromEmp = ref({
  username: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  deptId: '',
  entryDate: '',
  image: '',
  exprList:[{ 
    begin : '',
    end : '',
    job: '', 
    company: '', 
    exprDate: ''}]
})
// 员工经历表单
const empExprList=ref(
  {
    begin : '',
    end : '',
    job: '',
    company: '',
    exprDate: [],
  }
)
// 性别列表
const genderList = ref([
  { name: '男', value: 1 },
  { name: '女', value: 2 }
])
// 员工职位列表wei
const jobList = ref([
  { label: '班主任', value: 1 },
  { label: '讲师', value: 2 },
  { label: '学工主管', value: 3 },
  { label: '教研主管', value: 4 },
  { label: '咨询师', value: 5 },
  { label: '其他', value: 6 }
])
//部门列表
const deptList = ref([])
// 表单验证
const ruleEmpRef = ref('')
//表单校验规则
const empRules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2到20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ]
});
// 定义批量删除员工的ids数组
const delIds = ref([])
// 获取所有部门
const queryAll=async ()=>{
  const res = await queryAllDept();
  deptList.value = res.data; 
}
// 员工分页查询
const queryPage = async () => {
  const res = await queryPageApi(
    formEmp.value.name,
    formEmp.value.gender,
    formEmp.value.begin,
    formEmp.value.end,
    formEmp.value.page,
    formEmp.value.pageSize
  );
  empList.value = res.data.rows;
  total.value = res.data.total;
}
// 重置查询表单
const reset = () => {
  formEmp.value = {
    name: '',
    gender: '',
    entryDate: '',
    begin : '',
    end : '',
    page: 1,
    pageSize: 10
  }
  queryPage()
}
// 每页条数改变
const handleSizeChange = (val) => {
  formEmp.value.pageSize = val
  queryPage()
}
// 页码改变
const handleCurrentChange = (val) => {
  formEmp.value.page = val
  queryPage()
}
//侦听formEmpp中的date属性
watch(() => formEmp.value.entryDate,(newValue) => {
     if(formEmp.value.entryDate){
      formEmp.value.begin = newValue[0]
      formEmp.value.end = newValue[1]
     }else {
      formEmp.value.begin = ''
      formEmp.value.end = ''
     }
  }
)
// 侦听diglogFromEmp中的empExprList属性
watch(() => diglogFromEmp.value.exprList,(newValue) => {
  if(newValue && newValue.length > 0){ 
    newValue.forEach(item => {
      if(item.exprDate && item.exprDate.length > 0){
        item.begin = item.exprDate[0];
        item.end = item.exprDate[1];
  }
  })
  }
},{deep: true})
// 修改触发
const toEdit = async (id)=>{

  const res = await queryEmpByIdApi(id);
  if(res.data){ 
    dialogFormVisible.value = true
    dialogTitle.value = '修改员工'
    diglogFromEmp.value = res.data
  }
  // 对员工经历进行处理
  let exprList = res.data.exprList
  if(exprList && exprList.length > 0){ 
    exprList.forEach(item => {
      if(item.begin && item.end){
        item.exprDate = [item.begin,item.end]
      }
    })
  }
}
// 添加触发
const toAdd = () => {
  dialogTitle.value = '新增员工'
  diglogFromEmp.value = {
    username: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    deptId: '',
    entryDate: '',
    image: '',
    exprList: [{ 
      begin: '',
      end: '',
      job: '', 
      company: '', 
      exprDate: []
    }]
  }
  dialogFormVisible.value = true
}

//文件上传
// 图片上传成功后触发
const handleAvatarSuccess = (response,uploadFile) => {
  console.log(response)
  diglogFromEmp.value.image = response.data
}
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}
// 员工经历
// 添加员工经历
const addExprItem = () => {
   diglogFromEmp.value.exprList.push({
    begin : '',
    end : '',
    job: '',
    company: '',
    exprDate: []
  })
}
// 删除员工经历
const delExprItem = (index) => {
  diglogFromEmp.value.exprList.splice(index,1) // 删除索引为index的元素及之后的元素数量
}
// 添加修改员工
const saveEmp = async()=>{
  if(!ruleEmpRef.value.validate()) return
  try {
    await ruleEmpRef.value.validate()
    // 验证通过后执行添加操作
    let res = null;
    let msg = '';
    if(diglogFromEmp.value.id){  // 非空非0即为true
      res = await updateyEmpApi(diglogFromEmp.value); // 修改
      msg = '数据已修改'
    }else{ 
      res = await addEmpApi(diglogFromEmp.value); // 新增
       msg = '数据已添加'
    }
  
     if (res.code == 1) {
        ElNotification({
        title: '操作成功',
        message: msg,
        type: 'success',
      })
      dialogFormVisible.value = false
      queryPage()
    }
   
  } catch (error) {
    // 验证失败时的处理
    console.log('表单验证失败:', error)
    return false
  }
}
// 删除员工
const delEmp = async(id)=>{
  delIds.value.push(id)
  deleteByIds()
}
// 批量删除员工多选
const handleSelectionChange=(val) => {
  delIds.value = []
  val.forEach(item => {
    delIds.value.push(item.id)
  })
}
// 批量删除员工
const deleteByIds = async()=>{
  ElMessageBox.confirm(
    '是否删除选中的' + delIds.value.length + '条数据？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
       const res = await delEmpApi(delIds.value)
      if(res.code == 1){
        ElNotification({
        title: '删除成功',
        message: '数据已被删除',
        type: 'success',
      })
        queryPage()
      }
      else {
        ElNotification({
        title: '操作失败',
        message: "删除失败",
        type: 'error'})
      }
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    });
}
//声明token
const token = ref('')
// 图片上传携带token
const getToken = async () => {
 const loginUser = JSON.parse(localStorage.getItem('loginUser'));
  if(loginUser && loginUser.token){
    token.value = loginUser.token;
  }
}
// 钩子函数
onMounted(() => {
  queryPage()
  queryAll()
  getToken()
})
</script>

<template>
  <div class="emp-container">
    <div class="header-section">
      <h2 class="page-title">员工管理</h2>
    </div>
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="formEmp" class="demo-form-inline" label-width="80px" >
        <el-form-item label="姓名">
          <el-input v-model="formEmp.name" placeholder="请输入姓名" clearable style="width: 150px;" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            v-model="formEmp.gender"
            placeholder="请选择"
            clearable
            style="width: 120px;"
          >
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="入职时间">
          <el-date-picker
            v-model="formEmp.entryDate"
            type="daterange"
            value-format="YYYY-MM-DD"
            range-separator="到"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 300px;"
          />
          <el-button type="primary" @click="queryPage" style="margin-left: 10px;">查询</el-button>
          <el-button type="info" @click="reset">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作按钮区域 -->
    <el-card class="operation-card">
      <el-button type="primary" class="add-btn" @click="toAdd">
        <el-icon><Plus /></el-icon>
        新增员工
      </el-button>
      <el-button type="danger" class="del-btn" @click="deleteByIds">
        <el-icon><Minus /></el-icon>
        批量删除
      </el-button>
    </el-card>
    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table :data="empList" border stripe height="500px" class="emp-table" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="name" label="姓名" min-width="100"></el-table-column>
        <el-table-column prop="gender" label="性别" min-width="80">
          <template #default="scope">
            <el-tag type="primary" v-if="scope.row.gender === 1">
              <el-icon><Male /></el-icon>男</el-tag>
            <el-tag  type="danger" v-else>
              <el-icon><Female /></el-icon>女</el-tag>
          </template> 
        </el-table-column>
        <el-table-column prop="image" label="头像" min-width="100">
          <template #default="scope">
            <el-image style="width: 60px; height: 60px" :src="scope.row.image" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="部门名称" min-width="100"></el-table-column>
        <el-table-column prop="job" label="职位" min-width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.job === 1">班主任</el-tag>
            <el-tag v-else-if="scope.row.job === 2">讲师</el-tag>
            <el-tag v-else-if="scope.row.job === 3">学工主管</el-tag>
            <el-tag v-else-if="scope.row.job === 4">教研主管</el-tag>
            <el-tag v-else-if="scope.row.job === 5">咨询师</el-tag>
            <el-tag v-else>其他</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="entryDate" label="入职时间" min-width="100"></el-table-column>
        <el-table-column prop="updateTime" label="最后操作时间" min-width="150"></el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" class="table-btn" @click="toEdit(scope.row.id)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" class="table-btn" @click="delEmp(scope.row.id)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
     <!-- 添加修改员工 -->
      <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="750px">
        <!-- {{diglogFromEmp}} -->
        <el-form :inline="true" :model="diglogFromEmp" label-width="80px" class="demo-form-inline" ref="ruleEmpRef" :rules="empRules">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
            <el-input v-model="diglogFromEmp.username" placeholder="请输入用户名"  style="width: 218.4px;"  clearable />
          </el-form-item>
            </el-col>
            <el-col :span="12">
            <el-form-item label="姓名" prop="name">
            <el-input v-model="diglogFromEmp.name" placeholder="请输入员工姓名"  style="width: 218.4px;"  clearable />
          </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-select
                v-model="diglogFromEmp.gender"
                placeholder="请选择"
                clearable
              >
                <el-option v-for="item in genderList" :key="item.value" :label="item.name" :value="item.value" />
              </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
            <el-input v-model="diglogFromEmp.phone" placeholder="请输入员工手机号"  style="width: 218.4px;"  clearable />
          </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="职位">
            <el-select
                v-model="diglogFromEmp.job"
                placeholder="请选择"
                clearable
              >
                <el-option v-for="item in jobList" :label="item.label" :key="item.value" :value="item.value" />
              </el-select>
          </el-form-item>
            </el-col>
            <el-col :span="12">
            <el-form-item label="薪资">
            <el-input v-model="diglogFromEmp.salary" placeholder="请输入员工薪资"  style="width: 218.4px;"  clearable />
          </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属部门">
            <el-select
                v-model="diglogFromEmp.deptId"
                placeholder="请选择"
                clearable
              >
                <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.id" />
              </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入职日期">
            <el-date-picker
              v-model="diglogFromEmp.entryDate"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              clearable
            />
          </el-form-item>
            </el-col>
          </el-row>
          <!-- 头像上传 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="头像">
                <el-upload
                  class="avatar-uploader"
                  action="/api/upload"
                  :headers="{'token': token}"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :auto-upload="true"
                >
                <img 
                  v-if="diglogFromEmp.image" 
                  :src="diglogFromEmp.image" 
                  class="avatar" 
                  alt="头像预览"
                  style="width: 100px; height: 100px;"
                />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
                <div div class="upload-tip">点击上传头像，支持 JPG/PNG 格式，大小不超过 10MB</div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="工作经历">
                <!-- 工作经历 -->
                <el-button type="success" size="small" @click="addExprItem">+添加员工工作经历</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="5" v-for="(empExpr,index) in diglogFromEmp.exprList ">
            <el-col :span="10">
              <el-form-item label="时间" size="small" label-width="80px">
                <el-date-picker
                  v-model="empExpr.exprDate"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                  range-separator="到"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  clearable
                  style="width: 200px;" 
              />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="公司" label-width="60px" size="small" style="width: 190px;" >
                <el-input v-model="empExpr.company" placeholder="请输入公司名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="职位" label-width="60px" size="small" style="width: 170.4px;" >
                <el-input v-model="empExpr.job" placeholder="请输入职位名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item label="">
                <el-button type="danger"size="small" @click="delExprItem(index)">-删除</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
         <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="saveEmp()">保存</el-button>
          </span>
        </template>
      </el-dialog>
    
    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<style scoped>
.emp-container {
  padding: 20px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.page-title {
  color: #303133;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: none;
  display: flex;
  align-items: center;
}

.search-card :deep(.el-form) {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.search-card :deep(.el-form-item) {
  margin-bottom: 0;
  display: flex;
  align-items: center;
}


.operation-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: none;
}

.add-btn, .del-btn {
  padding: 10px 20px;
  margin-right: 10px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: none;
  margin-bottom: 20px;
}

.emp-table {
  width: 100%;
}

.emp-table :deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.emp-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.table-btn {
  margin: 0 5px;
}

.table-btn:first-child {
  margin-left: 0;
}

.table-btn:last-child {
  margin-right: 0;
}
  /* 图片上传 */
 .avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 100px;
  height: 100px;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 7px;
}
/* 响应式设计 */
@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-card :deep(.el-form) {
    flex-wrap: wrap;
  }
  
  .search-card :deep(.el-form-item) {
    margin-bottom: 15px;
  }
  
  .add-btn, .del-btn {
    margin-top: 10px;
    margin-left: 0;
  }
  
  .emp-table {
    font-size: 12px;
  }
  
  .table-btn span {
    display: none;
  }
  
  .table-btn .el-icon {
    margin-right: 0;
  }
}
</style>